package com.finger.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.finger.eduservice.entity.EduSubject;
import com.finger.eduservice.entity.excel.ExcelSubjectData;
import com.finger.eduservice.exception.GuliException;
import com.finger.eduservice.service.EduSubjectService;

import java.util.Map;

public class ExcelSubjectListener extends AnalysisEventListener<ExcelSubjectData> {

    private EduSubjectService eduSubjectService;

    public ExcelSubjectListener(){

    }
    public ExcelSubjectListener(EduSubjectService subjectService){
        this.eduSubjectService = subjectService;
    }


    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        if(excelSubjectData==null){
            throw new GuliException(20001,"数据为空");
        }
        EduSubject oneSubject = this.existsOneSubjectName(eduSubjectService, excelSubjectData.getOneSubjectName());

        if(oneSubject==null){
            oneSubject = new EduSubject();
            oneSubject.setTitle(excelSubjectData.getOneSubjectName());
            oneSubject.setParentId("0");
            eduSubjectService.save(oneSubject);
        }

        EduSubject twoSubject = this.existsTwoSubjectName(eduSubjectService, excelSubjectData.getTwoSubjectName(), oneSubject.getId());

        if(twoSubject==null){
            twoSubject = new EduSubject();

            twoSubject.setTitle(excelSubjectData.getTwoSubjectName());

            twoSubject.setParentId(oneSubject.getId());

            eduSubjectService.save(twoSubject);
        }

    }

    /**
     * 判断一级分类是否重复
     * @param eduSubjectService
     * @param oneSubjectName
     * @return
     */
    public EduSubject existsOneSubjectName(EduSubjectService eduSubjectService,String oneSubjectName){
        QueryWrapper wrapper = new QueryWrapper<>();

        wrapper.eq("title",oneSubjectName);

        wrapper.eq("parent_id",0);

        EduSubject oneSujectObj = eduSubjectService.getOne(wrapper);

        return oneSujectObj;
    }

    /**
     * 判断二级分类是否重复
     * @param eduSubjectService
     * @param twoSubjectName
     * @param pid
     * @return
     */
    public EduSubject existsTwoSubjectName(EduSubjectService eduSubjectService,String twoSubjectName,String pid){
        QueryWrapper wrapper = new QueryWrapper<>();

        wrapper.eq("title",twoSubjectName);

        wrapper.eq("parent_id",pid);

        EduSubject oneSujectObj = eduSubjectService.getOne(wrapper);

        return oneSujectObj;
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
